﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using myDNS;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace _edu_vn_rootDNS
{
    class Program
    {
        static void Main(string[] args)
        {
            int level = 3;
            DNSServer edu_vn_rootDNS = new DNSServer("EDU.VN.ROOT DNS ", "127.0.0.1", 103);
            edu_vn_rootDNS.ToString();
            do
            {
                UdpClient sock;
                int port = 100;
                IPEndPoint ep;
                try
                {


                    sock = new UdpClient(port);
                    ep = new IPEndPoint(0, 0);
                    byte[] recData = sock.Receive(ref ep);



                    string recString = Provider.GetString(recData);
                    HostName_IP_Port ip_port = Provider.GetHostName_IP_Port(recString);

                    IPEndPoint ipAskServer = new IPEndPoint(IPAddress.Parse(ip_port._ip), ip_port._port);
                    if (ip_port._hostName[0] == '1')
                    {
                        string hostName = recString.Substring(1, recString.Length - 1);
                        hostName = hostName.ToLower();

                        string strComp = Provider.GetStringCompare(hostName, level);
                        HostName_IP_Port resultSearch = edu_vn_rootDNS.SearchHostName(strComp, "DNS.txt");
                        if (resultSearch._ip == "0.0.0.0")
                        {
                            byte[] result = Provider.GetBytes("0.0.0.0");

                            sock.Send(result, result.Length, ipAskServer);
                            sock.Close();
                        }
                        else
                        {
                            byte[] resultByte = Provider.GetBytes("1" + resultSearch._ip + ":" + resultSearch._port);
                            // sock = new UdpClient();
                            sock.Send(resultByte, resultByte.Length, ipAskServer);
                            sock.Close();

                        }
                    }
                    else
                    {

                    }

                }
                catch (Exception ex)
                {
                    Console.Write(ex.Message.ToString());
                }
            }
            while (true);
        }
    }
}
